//
//  MessageViewViewController.m
//  Message
//
//  Created by Fanty on 13-12-17.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "MessageViewController.h"
#import <chameleon-ios-sdk/CApplication.h>
#import <chameleon-ios-sdk/MessageModel.h>
#import <chameleon-ios-sdk/CubeModel.h>
#import "CubeModule.h"
#import "CubesModel.h"
#import "MessageRecordHeaderView.h"
#import "MessageRecordCell.h"
#import "DataCenter+Cube.h"
#import "AnnouncementTableViewController.h"
#import "BSLCubeConstant.h"
#import <MainModuleSDK/MainUtils.h>

#import <SVProgressHUD/SVProgressHUD.h>

@interface MessageViewController ()<UITableViewDataSource,UITableViewDelegate,MessageRecordHeaderViewDelegate>
-(void)reloadGroupArray;
-(void)reloadMessageArray;

-(void)rightNavClick;
-(void)createRrightNavItem;

-(void)rightRefreshClick;

- (UIImage *)imageTransform:(UIImage *)image rotation:(UIImageOrientation)orientation;

-(void)cube_MessageUpdated:(NSNotification*)notification;
@end

@implementation MessageViewController

- (id)init{
    self = [super init];
    if (self) {
        
        groupArray=[[NSMutableArray alloc] initWithCapacity:2];
        messageArray=[[NSMutableArray alloc] initWithCapacity:2];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cube_MessageUpdated:) name:@"Cube_MessageUpdated" object:nil];
        
        
        self.title = @"消息推送";
        
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    selectedModuleIdentifier=nil;
    [self reloadGroupArray];

    
    self.view.backgroundColor=[UIColor whiteColor];

    [self initNavigation];
    
    CGRect rect=self.view.bounds;
    rect.origin.y=CGRectGetMaxY(navigationBar.frame);
    rect.size.height-=rect.origin.y;
    
    
    tableView=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    tableView.backgroundColor=[UIColor whiteColor];
    tableView.delegate=self;
    tableView.dataSource=self;

    UIView* v=[[UIView alloc] init];
    v.backgroundColor=[UIColor clearColor];
    tableView.tableFooterView=v;
    tableView.tableHeaderView=v;
    tableView.showsHorizontalScrollIndicator=NO;
    tableView.showsVerticalScrollIndicator=NO;

    
    [self.view addSubview:tableView];
    
    [self createRrightNavItem];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}


- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark method

-(void)rightNavClick{
    [tableView setEditing:!tableView.editing animated:YES];
    [self createRrightNavItem];
}

-(void)rightRefreshClick{
    
    refreshLoading=YES;
    
    [SVProgressHUD showWithStatus:@"正在同步消息..." maskType:SVProgressHUDMaskTypeBlack];
    
    CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    [cubeModule.messageManager syncMessage];
    [cubeModule.accountManager syncAuth:YES];
}

-(void)createRrightNavItem{
    /*
    if([groupArray count]<1){
        navigationItem.rightBarButtonItem=nil;
        return;
    }
     */
    
    NSMutableArray* array=[[NSMutableArray alloc] initWithCapacity:2];
    
    UIButton* backButton=[UIButton buttonWithType:UIButtonTypeCustom];
    
    backButton.frame=CGRectMake(0.0f, 0.0f, 60.0f, 44.0f);
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backButton setTitle:@"刷新" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(rightRefreshClick) forControlEvents:UIControlEventTouchUpInside];
    
    [array addObject:[[UIBarButtonItem alloc] initWithCustomView:backButton]];
    
    if([groupArray count]>0){
        UIButton* backButton2=[UIButton buttonWithType:UIButtonTypeCustom];
        
        backButton2.frame=CGRectMake(0.0f, 0.0f, 60.0f, 44.0f);
        [backButton2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [backButton2 setTitle:(tableView.editing?@"取消":@"编辑") forState:UIControlStateNormal];
        [backButton2 addTarget:self action:@selector(rightNavClick) forControlEvents:UIControlEventTouchUpInside];
        
        [array addObject:[[UIBarButtonItem alloc] initWithCustomView:backButton2]];
    }
    navigationItem.rightBarButtonItems=array;
    
//    navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backButton];


    
    //[self createRightNavigationItem:(tableView.editing?@"取消":@"编辑") target:self action:@selector(rightNavClick)];
}

- (UIImage *)imageTransform:(UIImage *)image rotation:(UIImageOrientation)orientation{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
}


-(void)reloadGroupArray{
    [groupArray removeAllObjects];
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    NSArray* array=[module.messageManager messageGroupList];
    if([array count]>0)
        [groupArray addObjectsFromArray:array];
}

-(void)reloadMessageArray{
    [messageArray removeAllObjects];
    if([selectedModuleIdentifier length]>0){
        CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
        NSArray* array=[module.messageManager messageList:selectedModuleIdentifier];
        [messageArray addObjectsFromArray:array];
    }
}

-(void)cube_MessageUpdated:(NSNotification*)notification{
    if(refreshLoading){
        refreshLoading=NO;
        [SVProgressHUD dismiss];
    }
    if([notification.object isKindOfClass:[NSNumber class]] && [notification.object boolValue]){
        [self reloadGroupArray];
        [self reloadMessageArray];
        [tableView reloadData];
        
        [self createRrightNavItem];
    }

}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)__tableView{
    return [groupArray count];
}

- (NSInteger)tableView:(UITableView *)__tableView numberOfRowsInSection:(NSInteger)section{
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier])
        return [messageArray count];
    else
        return 0.0f;
}

- (UITableViewCell *)tableView:(UITableView *)__tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageRecordCell *cell = [__tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[MessageRecordCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
    
    [cell title:messageModel.title content:messageModel.content time:messageModel.receiveTime isRead:messageModel.isRead];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)__tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
    
    return [MessageRecordCell cellHeight:messageModel.title content:messageModel.content width:__tableView.frame.size.width];
    
}

- (UIView *)tableView:(UITableView *)__tableView viewForHeaderInSection:(NSInteger)section{
    
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    
    MessageRecordHeaderView *headerView = [[MessageRecordHeaderView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 36)];
    headerView.delegate = self;
    headerView.section = section;
    headerView.moduleId = groupModel.moduleIdentifer;
    
    NSString* name=groupModel.moduleName;
    if([name length]<1){
        name=[[DataCenter defaultCenter] finidServiceCubeModule:groupModel.moduleIdentifer].name;
    }
    
    [headerView configureWithIconUrl:nil moduleName:name messageCount:[NSString stringWithFormat:@"%d",groupModel.totalCount] sectionIndenx:section withUnReadCount:[NSString stringWithFormat:@"%d",groupModel.unReadCount]];
    
    headerView.tag = section + 10;
    
    
    UIImageView* arrowImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Module.bundle/images/xmpp_arrow.png"]];
    arrowImageView.frame= CGRectMake(17, 15, 10, 11);
    if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
        arrowImageView.image  = [self imageTransform:arrowImageView.image rotation:UIImageOrientationRight];
    }
    [headerView addSubview:arrowImageView];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 36;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)__tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(__tableView.editing)
        return UITableViewCellEditingStyleDelete;
    return UITableViewCellEditingStyleNone;
}


//修改删除按钮的文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}


- (void)tableView:(UITableView *)__tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
        MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
        
        int newSelected=0;
        MessageGroupModel* groupModel=nil;
        for(MessageGroupModel* _groupModel in groupArray){
            if([_groupModel.moduleIdentifer isEqualToString:messageModel.moduleIdentifer]){
                groupModel=_groupModel;
                break;
            }
            newSelected++;
        }
        if(!messageModel.isRead){
            groupModel.unReadCount--;
        }
        groupModel.totalCount--;
        
        
        [module.messageManager removeMesageById:messageModel];
        [messageArray removeObject:messageModel];

        [__tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        
        if([messageArray count]<1 ){
            selectedModuleIdentifier=nil;

            [groupArray removeObjectAtIndex:newSelected];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:newSelected] withRowAnimation:UITableViewRowAnimationAutomatic];
                
            if([groupArray count]<1)
                [self createRrightNavItem];
            
        }
        else{
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:newSelected] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
}

- (void)tableView:(UITableView *)__tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [__tableView deselectRowAtIndexPath:indexPath animated:YES];

    MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
    if(!messageModel.isRead){
        messageModel.isRead=YES;
        CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
        [module.messageManager setIsReadMessageById:messageModel];
        [__tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        [groupArray enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){
            MessageGroupModel* groupModel=obj;
            if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
                groupModel.unReadCount--;
                [__tableView reloadSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        }];
    }
    
    if([messageModel.moduleIdentifer isEqualToString:@"com.foss.announcement"]){
        AnnouncementTableViewController* controller=[[AnnouncementTableViewController alloc] init];
        controller.messageId=messageModel.messageId;
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if([messageModel.messageType isEqualToString:@"SYS"] || [messageModel.messageType isEqualToString:@"SECURITY"]){
    }
    
/*
    else if([messageModel.moduleUrl length]>0){
        CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
        [module.messageManager checkApnsRedirectAndRedirect:messageModel  routingByMessageRecord:YES];
    }
 */
    else if(messageModel.busiDetail){
        if([[DataCenter defaultCenter] finidInstallCubeModule:messageModel.moduleIdentifer]==nil){
            UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"模块未安装，请下载该模块" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
        else{
            CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
            [module.messageManager checkApnsRedirectAndRedirect:messageModel  routingByMessageRecord:YES];
        }
    }
    
}

#pragma mark messagerecordheaderview delegate

-(void)shouldShowCellInModule:(NSString *)moduleId atIndex:(NSInteger)section{
    
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    moduleId=groupModel.moduleIdentifer;
    __block int oldSelected=-1;
    __block int newSelected=-1;

    if([moduleId isEqualToString:selectedModuleIdentifier]){
        selectedModuleIdentifier=nil;
        [groupArray enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){
            MessageGroupModel* groupModel=obj;
            if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
                oldSelected=(int)index;
            }
            else if([groupModel.moduleIdentifer isEqualToString:moduleId]){
                newSelected=(int)index;
            }
        }];
    }
    else{
        [groupArray enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){
            MessageGroupModel* groupModel=obj;
            if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
                oldSelected=(int)index;
            }
            else if([groupModel.moduleIdentifer isEqualToString:moduleId]){
                newSelected=(int)index;
            }
        }];
        selectedModuleIdentifier=moduleId;
    }
    
    
    [self reloadMessageArray];
    
    

    [tableView reloadData];
}


-(void)deleteModuleData:(NSString*)moduleId{
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Module"];
    
    int section=-1;
    int index=0;
    for(MessageGroupModel* p in groupArray){
        if([p.moduleIdentifer isEqualToString:moduleId]){
            section=index;
            break;
        }
        index++;
    }
    if(section<0)return;
    
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    [module.messageManager removeMessageByGroup:groupModel.moduleIdentifer];
    if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
        selectedModuleIdentifier=nil;
        [messageArray removeAllObjects];
    }
    [groupArray removeObjectAtIndex:section];

    [tableView deleteSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];

    if([groupArray count]<1){
        [self createRrightNavItem];
    }
}




@end
